#include "Auth.h"
#include <iostream>
#include <string>
#include <curl/curl.h>  
#include "easylogging++.h"
#include <chrono>  
#include <ctime>

size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    std::string* s = (std::string*)userp;
    s->append((char*)contents, size * nmemb);
    return size * nmemb;
}

Json::Value authInfo()
{
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if (curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://14.22.113.202:8084/data.json");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);

        /* Check for errors */
        if (res != CURLE_OK) {
            LOG(ERROR) << "curl_easy_perform() failed: " << curl_easy_strerror(res);
        }
        else {
            //std::cout << "Received data: " << readBuffer << std::endl;
        }
        /* always cleanup */
        curl_easy_cleanup(curl);
    }
    // 创建一个 Json::Reader 对象  
    //LOG(INFO) << "body:" << readBuffer;
    Json::Reader reader;
    Json::Value root;
    bool parsingSuccessful = reader.parse(readBuffer, root);
    if (!parsingSuccessful) {
        // 处理解析错误  
        LOG(ERROR) << "Failed to parse JSON: " << reader.getFormattedErrorMessages();
    }
    return root;
}

bool check(std::string uuid)
{
    Json::Value root = authInfo();
    Json::Value authInfo = root[uuid];

    // 获取当前时间点  
    auto now = std::chrono::system_clock::now();
    // 将时间点转换为从1970年1月1日开始的秒数  
    std::time_t now_time_t = std::chrono::system_clock::to_time_t(now);
    // 转换为 long 类型（如果需要的话）  
    long long_timestamp = static_cast<long>(now_time_t);
    long expireTime = static_cast<long>(authInfo["expireTime"].asInt64());
    return expireTime > long_timestamp;
}
